import React, { useRef, useState } from 'react';
import { FormInstance } from 'antd';
import ProCard from '@ant-design/pro-card';
import { PageContainer } from '@ant-design/pro-layout';
import { addOrg, loadOrg, updateOrg } from '@/pages/Enterprise/Org/service';
import { OrgBody, OrgItem } from '@/pages/Enterprise/Org/data';
import {
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-form';
import OrgList from '@/pages/Enterprise/Org/list';
import { ActionType } from '@ant-design/pro-table';

const OrgPage: React.FC = () => {
  const [orgId, setOrgId] = useState(0);
  const [editMode, setEditMode] = useState<'edit' | 'add' | 'readonly'>('add');
  const [parentList, setParentList] = useState<OrgItem[]>([]);
  const [defaultParent, setDefaultParent] = useState(0);
  const [formTitle, setFormTitle] = useState('添加部门');

  const orgRef = useRef<FormInstance>();
  const defaultFormData = {
    status: '0',
    orgName: undefined,
    orderNum: 0,
    mode: 'add',
    parentId: defaultParent,
  };
  const saveSubmit = async (values: OrgBody) => {
    try {
      if (editMode === 'edit') {
        values.orgId = orgId;
        await updateOrg(values);
      } else if (editMode === 'add') {
        await addOrg(values);
        orgRef.current?.resetFields();
      }
      actionRef.current?.reload();
    } catch (e) {
      return false;
    }
    return true;
  };

  const actionRef = useRef<ActionType>();
  // const userInfo = await initialState?.fetchUserInfo?.();

  return (
    <PageContainer waterMarkProps={{ content: '' }} header={{ title: '管理部门信息', ghost: true }}>
      <ProCard
        gutter={16}
        style={{ background: '#f0f2f5', margin: '0px' }}
        bodyStyle={{ padding: '0px' }}
      >
        <ProCard colSpan={12} ghost bodyStyle={{ minHeight: '600px' }}>
          <OrgList
            onChange={async (org) => {
              setOrgId(org.id);
              setEditMode('readonly');
              setFormTitle('查看部门信息');
            }}
            actionRef={actionRef}
            onDataLoad={(org) => {
              setParentList(org);
              setDefaultParent(org[0].id);
            }}
            onAction={(item, mode) => {
              if (mode === 'edit') {
                setOrgId(item.id);
                setEditMode('edit');
                setFormTitle('编辑部门信息');
              } else if (mode === 'add') {
                setOrgId(0);
                if (item.id == 0) {
                  setDefaultParent(parentList[0].id);
                } else {
                  setDefaultParent(item.id);
                }
                setEditMode('add');
                setFormTitle('新增部门');
              }
            }}
          />
        </ProCard>
        <ProCard colSpan={8} title={formTitle}>
          <ProForm<OrgBody>
            formRef={orgRef}
            layout={editMode === 'readonly' ? 'horizontal' : 'vertical'}
            onFinish={saveSubmit}
            submitter={{
              render: (props, dom) => {
                if (editMode === 'readonly') {
                  return null;
                }
                return dom;
              },
            }}
            params={{ orgId, time: Math.random() }}
            request={async (t) => {
              if (t.orgId > 0) {
                const { data } = await loadOrg(t.orgId);
                return data;
              } else {
                return new Promise<OrgBody>((resolve, reject) => {
                  resolve(defaultFormData as OrgBody);
                });
              }
            }}
          >
            <ProFormTreeSelect
              width="md"
              readonly={editMode === 'readonly'}
              request={async () => {
                return parentList;
              }}
              fieldProps={{
                treeLine: true,
                treeDefaultExpandAll: true,
                fieldNames: { label: 'label', value: 'id', children: 'children' },
                onChange: (value) => {
                  console.log(value);
                },
              }}
              name="parentId"
              label="上级部门"
            />
            <ProFormText
              width="md"
              readonly={editMode === 'readonly'}
              name="orgName"
              label="部门名称"
              // tooltip="最长为 24 位"
              placeholder="请输入部门名称"
            />

            <ProFormDigit
              label="排序"
              readonly={editMode === 'readonly'}
              name="orderNum"
              // tooltip="最长为 24 位"
              width="md"
              placeholder="请输入金额"
            />

            <ProFormRadio.Group
              name="status"
              readonly={editMode === 'readonly'}
              label="状态"
              options={[
                {
                  label: '启用',
                  value: '0',
                },
                {
                  label: '禁用',
                  value: '1',
                },
              ]}
            />
          </ProForm>
        </ProCard>
      </ProCard>
    </PageContainer>
  );
};

export default OrgPage;
